package com.kehutong.common;

import java.util.List;

import org.coraframework.json.JSONObject;
import org.coraframework.orm.jdbc.Page;

/**
 * Author:  peter
 * Date:    2020/7/23
 * Function:
 */
public class PageUtils {

    private static final int DEFAULT_PAGE_NO = 1;
    private static final int DEFAULT_PAGE_SIZE = 10;

    /**
     * 保留实体分页信息
     * 列表转为自定义json对象
     */
    public static <T> Page<T> parse(Page<?> data, List<T> result) {
        Page<T> page = new Page<>(data.getPageNo(), data.getPageSize());
        page.setList(result);

        page.setCount(data.getCount());
        return page;
    }

    /**
     * 查出所有结果后
     * 根据分页请求截取并构造Page对象
     */
    public static <T> Page<T> buildPage(JSONObject req, List<T> resultList) {

        Integer pageNo = req.getInteger("pageNo");
        if (pageNo == null) {
            pageNo = DEFAULT_PAGE_NO;
        }
        Integer pageSize = req.getInteger("pageSize");
        if (pageSize == null) {
            pageSize = DEFAULT_PAGE_SIZE;
        }

        Page<T> page = new Page<>(pageNo, pageSize);

        int fromIndex = (pageNo - 1) * pageSize;
        int toIndex = fromIndex + pageSize;

        fromIndex = Math.min(fromIndex, resultList.size());
        toIndex = Math.min(toIndex, resultList.size());

        List<T> subList = resultList.subList(fromIndex, toIndex);
        page.setList(subList);

        page.setCount(resultList.size());
        return page;
    }
    /**
     * 直接封装、不对数据分页
     * 查出所有结果后
     * 根据分页请求截取并构造Page对象
     */
    public static <T> Page<T> toBuildPage(JSONObject req, List<T> resultList) {
        Integer pageNo = req.getInteger("pageNo");
        if (pageNo == null) {
            pageNo = DEFAULT_PAGE_NO;
        }
        Integer pageSize = req.getInteger("pageSize");
        if (pageSize == null) {
            pageSize = DEFAULT_PAGE_SIZE;
        }
        Page<T> page = new Page<>(pageNo, pageSize);
        page.setList(resultList);
        page.setCount(resultList.size());
        return page;
    }
}
